//
//  VOLHouseLocationViewController.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLHouseLocationViewController.h"
#import "common.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <AddressBook/AddressBook.h>

#import "VOLAppDelegate.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#define CodeHTTP @"http://restapi.amap.com/v3/geocode/geo?"     //地理编码
#define key @"f139551450d4970194492a925c6b420c"

@interface VOLHouseLocationViewController ()
{
    CLLocationManager *locationManager;
    VOLAppDelegate *del;
    
    NSString *oldAddress;
    
    NSString *stringAddressLocation;
    NSString *stringAddressInput;
    JSONDecoder *json;
}

@end

@implementation VOLHouseLocationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    del = kGetDel;
    
    //标题
    self.title = @"位置";
    
    //设置返回按钮,并实现goBack:方法
    addBackButton();
    
    [self.nextButton setBackgroundColor:kThemeColor];
    
    //设置输入框代理
    self.cityField.delegate = self;
    self.streetField.delegate = self;
    
    //定位
#pragma mark 定位初始化
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //设置代理
    locationManager.delegate = self;
    
#pragma mark 地图初始化
    //设置代理
    self.locationMap.delegate = self;
    //设置是否显示用户当前位置
    self.locationMap.showsUserLocation = YES;
    //设置地图显示类型
    self.locationMap.mapType = MKMapTypeStandard;
    
    //开始定位
    [locationManager startUpdatingLocation];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    NSLog(@"memory waring");
}

#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark 跳转时记录参数
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    del.publishHouse.houseProvince = self.provinceField.text;
    del.publishHouse.houseCity = self.cityField.text;
    del.publishHouse.houseStreet = self.streetField.text;
    
    stringAddressInput = [NSString stringWithFormat:@"%@%@%@",self.provinceField.text,self.cityField.text,self.streetField.text];
#pragma mark 如果两个地址不同，则将输入放入的地址进行地理编码，记录下经纬度。
    if (![oldAddress isEqualToString:stringAddressInput]) {
        NSString *urlString = [NSString stringWithFormat:@"%@address=%@&output=json&key=%@",CodeHTTP,stringAddressInput,key];
        NSString *string = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:string];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        
        NSData *data = [request responseData];
        json = [[JSONDecoder alloc] init];
        NSDictionary *dic = [json objectWithData:data];
        NSArray *arr = [dic objectForKey:@"geocodes"];
        
        NSDictionary *dic1 = [arr objectAtIndex:0];
        NSString *locationStr = [dic1 objectForKey:@"location"];
        NSArray *locationArray = [locationStr componentsSeparatedByString:@","];
        del.publishHouse.houseLongitude = [locationArray[0] floatValue];
        del.publishHouse.houseLatitude = [locationArray[1] floatValue];
    }
}

#pragma mark 收回键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark 自定义方法，设置地图位置
-(void)setShowMapLongitude:(double)longitude latitude:(double)latitude{
    //设置经纬度，先纬度，后经度
    //    CLLocationCoordinate2D coord = {34.77,112.98};
    CLLocationCoordinate2D coord = {latitude,longitude};
    
    //设置显示范围精度
    MKCoordinateSpan span = {0.05,0.05};
    
    //显示范围
    MKCoordinateRegion region = {coord,span};
    
    //给地图设置显示区域
    [self.locationMap setRegion:region animated:YES];
    
}

#pragma mark 定位代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //获取位置的对象
    CLLocation *location = [locations firstObject];
    //经纬度
    double longitude = location.coordinate.longitude;
    double latitude = location.coordinate.latitude;
    
    //城市、街道信息
    //    NSString *cityInfo,*streetInfo;
    
    //位置反编码，可以得到当前的位置信息
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark *place in placemarks) {
            //            oldAddress = place.name;
            NSString *country = place.country;
            NSString *province = place.administrativeArea;
            NSString *city = place.locality;
            NSString *subCity = place.subLocality;
            NSString *street = place.thoroughfare;
            NSString *subStreet = place.subThoroughfare;
            
            //            NSLog(@"subAdministrativeArea = %@",place.subAdministrativeArea);
            //            NSLog(@"postalCode = %@",place.postalCode);
            //            NSLog(@"ISOcountryCode = %@",place.ISOcountryCode);
            //            NSLog(@"inlandWater = %@",place.inlandWater);
            //            NSLog(@"ocean = %@",place.ocean);
            //            NSLog(@"areasOfInterest = %@",place.areasOfInterest);
            
            NSString *provinceInfo = [NSString stringWithFormat:@"%@%@",country,province];
            //            NSString *cityInfo = [NSString stringWithFormat:@"%@%@%@",country,province,city];
            NSString *streetInfo = [NSString stringWithFormat:@"%@%@",subCity,street];
            
            if (subStreet != NULL) {
                streetInfo = [streetInfo stringByAppendingString:subStreet];
            }
            self.provinceField.text = provinceInfo;
            self.cityField.text = city;
            self.streetField.text = streetInfo;
            
            oldAddress = [NSString stringWithFormat:@"%@%@%@",provinceInfo,city,streetInfo];
            //            stringAddressInput = [NSString stringWithFormat:@"%@%@%@",self.provinceField.text,self.cityField.text,self.streetField.text];
        }
    }];
    //停止定位
    [locationManager stopUpdatingLocation];
    //记录经纬度
    del.publishHouse.houseLongitude = longitude;
    del.publishHouse.houseLatitude = latitude;
    
    
    //设置地图位置
    [self setShowMapLongitude:longitude latitude:latitude];
}


#pragma mark TextField代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}


@end










